<script lang="ts" setup>
import { onMounted, ref } from 'vue';

import { Select, Spin } from 'ant-design-vue';
import { debounce } from 'lodash-es';

import { tycSearch } from '#/api/company/tyc';

// interface Props {
//   modelName?: 'id' | 'name';
// }
//
// const props = withDefaults(defineProps<Props>(), {
//   modelName: 'name',
// });

const emit = defineEmits(['blur', 'change', 'select']);
const loading = ref(false);
// const isLoaded = ref(false);
const notFoundContent = ref<any>(null);
const currCompanyName = ref('');
const companyList = ref<any[]>([]);
const modelValue = defineModel<string>('value', {
  default: () => undefined,
});

onMounted(async () => {
  //
});

const getTycCompanyList = debounce(async (name: string) => {
  currCompanyName.value = name;
  if (!name) return;
  companyList.value = [];
  // console.log('搜索公司名：', name);
  loading.value = true;

  const list = (await tycSearch(name)) ?? [];
  if (currCompanyName.value === name) {
    companyList.value = list.map((item) => {
      return { label: item.name, value: item.name };
    });
    notFoundContent.value = list?.length > 0 ? null : '没有查到公司信息';
  }
  loading.value = false;
}, 300);

async function handleSearch(val: string) {
  if (!val) return;
  console.log(val);
  await getTycCompanyList(val);
}

async function handleChange(val: any) {
  console.log(val);
  currCompanyName.value = val;
  emit('change', modelValue.value);
}

async function handleSelect(val: any) {
  console.log(val);
  emit('select', val);
}
</script>
<template>
  <Select
    v-model:value="modelValue"
    class="w-full"
    placeholder="从天眼查搜索企业"
    show-search
    :show-arrow="false"
    :filter-option="false"
    :default-active-first-option="false"
    :not-found-content="loading ? undefined : notFoundContent"
    :options="companyList"
    @blur="emit('blur')"
    @change="handleChange"
    @search="handleSearch"
    @select="handleSelect"
  >
    <template v-if="loading" #notFoundContent>
      <Spin size="small" />
    </template>
  </Select>
</template>
